import Guid from "../common/guid";
import service from "../common/service";
import  useService from '@/hooks/useService';
import { useMainStore } from "../store/modules/store";
export interface UploadOption {
	file ?: {
		ext ?: string;
		url ?: string;
		name ?: string;
		type ?: string;
		guid ?: string;
	}
	UniqueKey?:string;
	UploadMethodName?:string;
	ModuleCode?:string;
	uploadUserNo ?: string;
	customExecUniqueKey ?: string;
	customExecMethodName ?: string;
	fileUploadPath ?: string;
	extendInfo ?: string;
	initParams ?: string;
	bucket ?: string;
	customParams ?: { [key : string] : string };
}

interface ILoginInfo {
    sUser: string;
    access_token?: string;
}
function useUpload(proxy?: { prefix?: string }) {
	const prefix = proxy?.prefix || "mainApi";
	const mainService = useService({ prefix });
	const mainStore = useMainStore();
	const { loginInfo } = mainStore;
	const cacheData = async function (guid ?: string, cacheValue ?: any) {
		const objectData = {
			CacheKey: `fileInfo|${guid}`,
			CacheTime: 60,
			CacheValue: JSON.stringify(cacheValue)
		}
		const res = await mainService.request('系统框架', 'CacheData', objectData);
		if(res===null){
			return true;
		}
		else{
			return false;
		}
	}

	const upload = async (opt ?: UploadOption) : Promise<{ guid ?: string, url ?: string }> => {
		const guid = opt.file.guid || Guid.NewGuid().ToString();
		const file = opt?.file;
		const { url } = file || {};
		const ext = file?.ext || url?.split('.').pop();
		const defaultFileName = `${guid}.${ext}`
		const cacheValue = {
			LastChunk: true,
			FirstChunk: true,
			StartByte: 0,
			FileName: defaultFileName,
			UploadUserNo: opt.uploadUserNo || '',
			UploadTime: new Date().toISOString(),
			ExtendInfo: opt.extendInfo || '',
			FileSaveMode: 1,
			IsUseMongdb: true,
			FileUploadPath: opt.fileUploadPath || '',
			InitParams: opt.initParams || opt.extendInfo || '',
			CustomExecUniqueKey: opt.customExecUniqueKey || '',
			CustomExecMethodName: opt.customExecMethodName || '',
			UniqueKey: opt.UniqueKey||'系统框架',
			UploadMethodName: opt.UploadMethodName||'UpLoadFile',
			ModuleCode:opt.ModuleCode || null,
			ExecAfterUpload: false,
			ServerName: null,
			ServiceName: null,
		}
		const cacheResult = await cacheData(guid, cacheValue);
		if (!cacheResult) {
			return null;
		}
		//const uploadurl = `${service.getFullUrl('file/uploadfilenew')}?fileinfo=fileInfo|${guid}&firstchunk=True&lastchunk=True&startbyte=0`;
		const uploadurl = mainService.getUploadFileUrl()+`/file/uploadfilenew?fileinfo=fileInfo|${guid}&firstchunk=True&lastchunk=True&startbyte=0`;
		console.log("uploadurl: " + JSON.stringify(uploadurl));
		const result = new Promise((resolve, reject) => {
			const uploadTask = uni.uploadFile({
				url: uploadurl,
				filePath: url,
				name: defaultFileName,
				header: { 'Authorization': `Bearer ${loginInfo.access_token}` },
				success(res) {
					console.log("res: " + JSON.stringify(res));
					let data = {}
					try {
						data = {
							guid: JSON.parse(res.data).ObjectData,
							url: mainService.getUploadFileUrl()+`/file/downloadfile/${JSON.parse(res.data).ObjectData}`
						}
					} catch (e) {
						if (res.statusCode != 200) {
							uni.showToast({
								duration: 3500,
								icon: 'none',
								title: '上传失败,请重试或检查配置,状态码:'+res.statusCode+' !',
								mask: true,
							});
						} else {
							if(JSON.parse(res.data).HasException){
								uni.showToast({
									duration: 3500,
									icon: 'none',
									title: JSON.parse(res.data).Exception.Message,
									mask: true,
								});
							}
						}
						throw (data);
					}
					if (res.statusCode == 200) {
						resolve(data)
					} else {
						uni.showToast({
							duration: 3500,
							icon: 'none',
							title: '上传失败,请重试或检查配置,状态码:'+res.statusCode+' !',
							mask: true,
						});
						reject(data)
					}
				},
				fail(res) {
					console.log("err: " + JSON.stringify(res));
					uni.showToast({
						duration: 3500,
						icon: 'none',
						title: '上传失败,请重试或检查配置!',
						mask: true,
					});
					reject(res)
				}
			})
			// uploadTask.onProgressUpdate(async (res) => {
			//     for (let i = 0, len = fileList.length; i < len; i++) {
			//         if (fileList[i]['upload_percent'] != 100) {
			//             fileList[i]['upload_percent'] = await res.progress
			//         }
			//     }
			// })
		});
		return result;

	};

	const remove = async (fileGuid : string) => {

		const res = await mainService.request('系统框架', 'DeleteFile', fileGuid);
		if(res){
			return true;
		}
		else{
			return false;
		}
	}


	const fetchFile = async (billId : string, billType : string, proxy?: { customFetchUniqueKey?: string; customFetchMethodName?: string; }) => {
		if(proxy?.customFetchUniqueKey && proxy?.customFetchMethodName) {
			const fetchReq = { FileId: billId, FileClass: billType };
			const fetchRes = await mainService.request(proxy?.customFetchUniqueKey, proxy?.customFetchMethodName, fetchReq);
			return fetchRes;
		} else {
			const req = {
				c_bill_type: billType, c_bill_id: billId
			};
			const res = await mainService.request('系统框架', 'GetAccessoryInfos', req);
			return res?res:[];
		}
	};

	return {
		upload,
		remove,
		fetchFile
	}
}

export default useUpload;